#pragma once

#include "hash.h"

template<typename K>
class HashFunc;

namespace byh
{
	template<typename K, typename V, typename Hash = HashFunc<K>>
	class unordered_map
	{
		struct KeyOfMap
		{
			const K& operator()(const pair<K, V>& kv)
			{
				return kv.first;
			}
		};
	public:
		using iterator = typename hash_bucket::HashTable<K, pair<const K, V>, KeyOfMap, Hash>::iterator;
		using const_iterator = typename hash_bucket::HashTable<K, pair<const K, V>, KeyOfMap, Hash>::const_iterator;
		using Node = hash_bucket::HashNode<pair<const K, V>>;

		pair<iterator, bool> insert(const pair<K, V>& kv)
		{
			return _table.insert(kv);
		}

		Node* find(const K& key)
		{
			return _table.find(key);
		}

		void erase(const K& key)
		{
			return _table.erase(key);
		}

		iterator begin()
		{
			return _table.begin();
		}

		iterator end()
		{
			return _table.end();
		}

		const_iterator begin() const
		{
			return _table.begin();
		}

		const_iterator end() const
		{
			return _table.end();
		}

		V& operator[](const K& key)
		{
			pair<iterator, bool> it = this->insert(make_pair(key, V()));
			return it.first->second;
		}

	private:
		hash_bucket::HashTable<K, pair<const K, V>, KeyOfMap, Hash> _table;
	};

	void Test_unordered_map()
	{
		unordered_map<string, int> m;
		vector<string> v = { "apple", "apple", "banana", "watermelon", "banana" };
		for (auto& e : v) m[e] ++;
		unordered_map<string, int>::iterator it = m.begin();
		while (it != m.end())
		{
			cout << it->first << " " << it->second << endl;
			++it;
		}
		cout << endl;

		cout << m.find("apple") << endl;
		cout << m.find("abdsaf") << endl;
		m.erase("apple");
		cout << m.find("apple") << endl;
	}
}